package com.ruoyi.collection.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.base.yaml.BusinessConfig;
import com.ruoyi.bizsys.domain.LoanIou;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.bizsys.vo.CollectionReduceOrderVo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.bizsys.domain.CollectionReduceOrder;
import com.ruoyi.bizsys.service.ICollectionReduceOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 催收减免订单Controller
 *
 * @author african-loan
 * @date 2022-08-15
 */
@RestController
@RequestMapping("/forcollection/collectionReduceOrder")
public class CollectionReduceOrderController extends BaseController {
    @Autowired
    private ICollectionReduceOrderService collectionReduceOrderService;
    @Autowired
    ILoanIouService loanIouService;

    @Autowired
    BusinessConfig businessConfig;
    private static RestTemplate restTemplate;
    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(180000);
        factory.setReadTimeout(180000);
        restTemplate = new RestTemplate(factory);
    }


    /**
     * 查询催收减免订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CollectionReduceOrder collectionReduceOrder) {
        startPage();
        List<CollectionReduceOrderVo> list = collectionReduceOrderService.selectCollectionReduceOrderVoList(collectionReduceOrder);
        // List<CollectionReduceOrder> list = collectionReduceOrderService.selectCollectionReduceOrderList(collectionReduceOrder);
        return getDataTable(list);
    }

    /**
     * 导出催收减免订单列表
     */
    @Log(title = "催收减免订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CollectionReduceOrder collectionReduceOrder) {
        List<CollectionReduceOrder> list = collectionReduceOrderService.selectCollectionReduceOrderList(collectionReduceOrder);
        ExcelUtil<CollectionReduceOrder> util = new ExcelUtil<CollectionReduceOrder>(CollectionReduceOrder.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 获取催收减免订单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(collectionReduceOrderService.selectCollectionReduceOrderById(id));
    }

    /**
     * 新增催收减免订单
     */
    @Log(title = "催收减免试算", businessType = BusinessType.INSERT)
    @PostMapping("/trial")
    public AjaxResult trial(@RequestBody CollectionReduceOrder collectionReduceOrder) {
        // 检查是否有审批中的减免申请：有减免申请正在审核中；
        CollectionReduceOrder collectionReduceOrderOnAppley = collectionReduceOrderService.selectOnAppleyingByLoanNo(collectionReduceOrder.getLoanSerialNo());
        if (null != collectionReduceOrderOnAppley) {
            return AjaxResult.error("There is an exemption application under review");
        }
        // 借据有未使用的减免，请联系客户还款
        CollectionReduceOrder collectionReduceOrderNotUse = collectionReduceOrderService.selectNotUseByLoanNo(collectionReduceOrder.getLoanSerialNo());
        if (null != collectionReduceOrderNotUse) {
            return AjaxResult.error("There are unused discounts on the loan order. Please contact the customer for repayment");
        }
        LoanIou loanIou = loanIouService.getLoanIouByLoanSerialNo(collectionReduceOrder.getLoanSerialNo());
        if (null == loanIou) {
            return AjaxResult.error("");
        }
        if (LoanIou.LOAN_IOU_STATUS_SETTLE == loanIou.getIouStatus()) {
            return AjaxResult.error("IOU has been settled");
        }
        if (LoanIou.LOAN_IOU_STATUS_NORMAL == loanIou.getIouStatus()) {
            return AjaxResult.error("IOU is not overdue, please refresh");
        }
        //检查剩余还款金额是否大于应还罚息：
        //是，则计算罚息减免金额=应还罚息*罚息减免比例，弹窗显示借据可减免金额=罚息减免金额；
        //否，则计算剩余还款减免金额=剩余还款金额*剩余还款金额减免比例，弹窗显示借据可减免金额=剩余还款减免金额；
        BigDecimal leftAmt = LoanIou.calculationOverdueAmount(loanIou);
        BigDecimal allLateFee = loanIou.getLateFee();
        JSONObject res = new JSONObject();
        BigDecimal trialAmt = BigDecimal.ZERO;
        if (leftAmt.compareTo(allLateFee) > 0) {
            ////是，则计算罚息减免金额=应还罚息*罚息减免比例，弹窗显示借据可减免金额=罚息减免金额；
            trialAmt = loanIou.getLateFee().multiply(collectionReduceOrder.getLateFeeReduceRate());
            res.put("exemption",trialAmt);
        } else {
            //否，则计算剩余还款减免金额=剩余还款金额*剩余还款金额减免比例，弹窗显示借据可减免金额=剩余还款减免金额；
            trialAmt = leftAmt.multiply(collectionReduceOrder.getRemainingRepayAmtRate());
            res.put("exemption",trialAmt);
        }
        res.put("loanSerialNo",collectionReduceOrder.getLoanSerialNo());
        res.put("repaymentAmount",leftAmt);
        res.put("amountDue",leftAmt.subtract(trialAmt));
        res.put("exemptionDeadline",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,
                DateUtils.addDays(new Date(), collectionReduceOrder.getReduceValidDays())
        ));
        return AjaxResult.success(res);
    }

    /**
     * 新增催收减免订单
     */
    @Log(title = "催收减免订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody CollectionReduceOrder collectionReduceOrder) {
        // 检查是否有审批中的减免申请：有减免申请正在审核中；
        CollectionReduceOrder collectionReduceOrderOnAppley = collectionReduceOrderService.selectOnAppleyingByLoanNo(collectionReduceOrder.getLoanSerialNo());
        if (null != collectionReduceOrderOnAppley) {
            return AjaxResult.error("There is an exemption application under review");
        }
        // 借据有未使用的减免，请联系客户还款
        CollectionReduceOrder collectionReduceOrderNotUse = collectionReduceOrderService.selectNotUseByLoanNo(collectionReduceOrder.getLoanSerialNo());
        if (null != collectionReduceOrderNotUse) {
            return AjaxResult.error("There are unused discounts on the loan order. Please contact the customer for repayment");
        }
        LoanIou loanIou = loanIouService.getLoanIouByLoanSerialNo(collectionReduceOrder.getLoanSerialNo());
        if (null == loanIou) {
            return AjaxResult.error("");
        }
        if (LoanIou.LOAN_IOU_STATUS_SETTLE == loanIou.getIouStatus()) {
            return AjaxResult.error("IOU has been settled");
        }
        if (LoanIou.LOAN_IOU_STATUS_NORMAL == loanIou.getIouStatus()) {
            return AjaxResult.error("IOU is not overdue, please refresh");
        }
        //检查剩余还款金额是否大于应还罚息：
        //是，则计算罚息减免金额=应还罚息*罚息减免比例，弹窗显示借据可减免金额=罚息减免金额；
        //否，则计算剩余还款减免金额=剩余还款金额*剩余还款金额减免比例，弹窗显示借据可减免金额=剩余还款减免金额；
        BigDecimal leftAmt = LoanIou.calculationOverdueAmount(loanIou);
        logger.info("leftAmt:{}",leftAmt);
        if (null != collectionReduceOrder.getReduceAmt()) {
            logger.info("输入金额：{}",collectionReduceOrder.getReduceAmt());
            if (collectionReduceOrder.getReduceAmt().compareTo(BigDecimal.ZERO) <= 0) {
                return AjaxResult.error("The amount entered is invalid");
            }
            //检查提交的减免金额是否大于剩余还款金额：
            //是，则提示减免金额超过限制，请重新提交；
            //否，则提交减免金额和减免截止日期，生成待审批的催收减免订单，并提示减免申请已提交，请等待审批；
            if (collectionReduceOrder.getReduceAmt().compareTo(leftAmt) > 0) {
                return AjaxResult.error("The amount of exemption exceeds the limit, please resubmit");
            }else{
                return createWaitApplyOrder(collectionReduceOrder,loanIou);
            }
        }
        BigDecimal allLateFee = loanIou.getLateFee();
        if (leftAmt.compareTo(allLateFee) <= 0) {
            //否，则计算剩余还款减免金额=剩余还款金额*剩余还款金额减免比例，弹窗显示借据可减免金额=剩余还款减免金额；
            collectionReduceOrder.setReduceAmt(leftAmt.multiply(collectionReduceOrder.getRemainingRepayAmtRate()));
        } else {
            //是，则计算罚息减免金额=应还罚息*罚息减免比例，弹窗显示借据可减免金额=罚息减免金额；
            collectionReduceOrder.setReduceAmt(loanIou.getLateFee().multiply(collectionReduceOrder.getLateFeeReduceRate()));
        }
        collectionReduceOrder.setCollectionReduceOrderId(IdWorker.getId());
        collectionReduceOrder.setActionType(CollectionReduceOrder.ACTION_TYPE_COLLECTION);
        collectionReduceOrder.setCustNo(loanIou.getCustNo());
        collectionReduceOrder.setStatus(CollectionReduceOrder.ORDER_STATUS_SUCCED);
        // 减免截止日期=当前时间+减免有效期天数；
        collectionReduceOrder.setExpTimeAt(DateUtils.addDays(new Date(), collectionReduceOrder.getReduceValidDays()));
        int rows = collectionReduceOrderService.insertCollectionReduceOrder(collectionReduceOrder);
        if (1 == rows) {
            // 触发短信到用户注册手机号提醒已减免尽快还款
            sendExemptionSms(loanIou, collectionReduceOrder.getReduceAmt());
            return AjaxResult.success("The exemption is successful. Please contact the customer as soon as possible to pay the remaining amount");
        } else {
            return AjaxResult.error();
        }

    }

    /**
     * 发送短信
     * @param loanIou
     * @param reduceAmt
     */
    private void sendExemptionSms(LoanIou loanIou, BigDecimal reduceAmt) {
        BigDecimal collectAmt = LoanIou.calculationOverdueAmount(loanIou);
        BigDecimal exemptionAmt = reduceAmt;

        String url = businessConfig.getApiurl()+"/forcollection/collection/sendExemptionSms?custNo="+loanIou.getCustNo()+"&collectAmt="+collectAmt+"&exemptionAmt="+exemptionAmt;
        logger.info("发送短信:"+url);
        restTemplate.getForObject(url,JSONObject.class,"");
    }

    private AjaxResult createWaitApplyOrder(CollectionReduceOrder collectionReduceOrder,LoanIou loanIou) {
        collectionReduceOrder.setCollectionReduceOrderId(IdWorker.getId());
        collectionReduceOrder.setActionType(CollectionReduceOrder.ACTION_TYPE_COLLECTION);
        collectionReduceOrder.setCustNo(loanIou.getCustNo());
        collectionReduceOrder.setStatus(CollectionReduceOrder.ORDER_STATUS_WAITING_PASS);
        // 减免截止日期=当前时间+减免有效期天数；
        collectionReduceOrder.setExpTimeAt(DateUtils.addDays(new Date(), collectionReduceOrder.getReduceValidDays()));
        int rows = collectionReduceOrderService.insertCollectionReduceOrder(collectionReduceOrder);
        if (1 == rows) {
            return AjaxResult.success("The application for exemption has been submitted. Please wait for approval");
        } else {
            return AjaxResult.error();
        }

    }

    /**
     * 修改催收减免订单
     */
    @Log(title = "催收减免订单", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody CollectionReduceOrder collectionReduceOrder) {
        CollectionReduceOrder collectionReduceOrderSql = collectionReduceOrderService.selectCollectionReduceOrderById(collectionReduceOrder.getId());
        boolean isUpdate = collectionReduceOrderService.updateById(collectionReduceOrder);
        if(isUpdate && CollectionReduceOrder.ORDER_STATUS_SUCCED == collectionReduceOrder.getStatus()){
            LoanIou loanIou = loanIouService.getLoanIouByLoanSerialNo(collectionReduceOrderSql.getLoanSerialNo());
            if (null == loanIou) {
                return AjaxResult.error("");
            }
            // 触发短信到用户注册手机号提醒已减免尽快还款
            sendExemptionSms(loanIou, collectionReduceOrderSql.getReduceAmt());
        }
        return toAjax(isUpdate ? 1 : 0);
    }
}